<template>
    <div class="setting-container">
         <van-nav-bar
        class="app-nav-bar"
        title="个人设置"
        left-arrow
        @click-left="onClickLeft"
        />
        <van-uploader  class="uploadImg" :after-read="afterRead" >
            <van-cell  is-link center title="头像">
              <van-image
                width="40"
                height="40"
                round
                :src="userInfo.photo"
                slot="default"
                />
            </van-cell>
        </van-uploader>
        
        <van-cell @click="ShowSettingUserName(userInfo.name)" title="昵称" is-link  >
            <span slot="default">{{ userInfo.name }}</span>
        </van-cell>
        <van-cell title="简介" @click="ShowSettingUserTro(userInfo.intro)" is-link >
            <span slot="default">{{ userInfo.intro ? userInfo.intro : '未填写' }}</span>
        </van-cell>
        <div class="split"></div>
        <van-cell title="性别" @click="showSexPick = true" is-link>
            <span slot="default">{{ userInfo.gender === 1 ? '女' : '男' }}</span>
        </van-cell>
        <van-cell title="生日" @click="pickDate" is-link>
            <span slot="default">{{ userInfo.birthday }}</span>
        </van-cell>




        <van-button @click="logOut" class="logout"  round type="info">退出登录</van-button>


        <!-- 修改昵称 -->
        <van-popup
        class="commentPopup"
        v-model="isShowSettingUserName"
        closeable
        close-icon="close"
        position="bottom"
        round
        >
        <div class="comment-content">
            <div class="popup-header">
                <p>修改昵称</p>
            </div>
            <div class="comment-input">
                <textarea  placeholder="请输入昵称" v-model="userName" />
            </div>
            <van-button 
              :disabled = " !userName ? true : false" 
              class="comment-btn"  
              round block 
              type="info" 
              @click="changeUserName"
              >
              修改
              </van-button>
        </div>
        
        
        </van-popup>
        <!-- 修改昵称 -->

        <!-- 修改简介 -->
         <!-- 修改昵称 -->
        <van-popup
        class="commentPopup"
        v-model="isShowSettingUserTro"
        closeable
        close-icon="close"
        position="bottom"
        round
        >
        <div class="comment-content">
            <div class="popup-header">
                <p>修改简介</p>
            </div>
            <div class="comment-input">
                <textarea  placeholder="请输入简介" v-model="userTro" />
            </div>
            <van-button 
              :disabled = " !userTro ? true : false" 
              class="comment-btn"  
              round block 
              type="info" 
              @click="changeUserTro"
              >
              修改
              </van-button>
        </div>
        
        
        </van-popup>
        <!-- 修改简介 -->

        <!-- // 事件选择器 -->
        <van-calendar 
           v-model="showDate" 
           color="#1989fa"
           :min-date="minDate" 
           :max-date="maxDate"
           @confirm="onDateConfirm" 
        />

        <!-- 时间选择器 -->

        <!-- 性别选择器 -->
        <van-popup v-model="showSexPick"
            position="bottom"
            round>
            <van-picker
            title="选择性别"
            show-toolbar
            :default-index="0"
            :columns="columns"
            @confirm="onConfirm"
            @cancel="onCancel"
            />
        </van-popup>
        <!-- 性别选择器 -->

        <!-- 图像裁切遮罩层 -->
        <!-- <van-overlay :show="show" @click="show = false">
            <div class="wrapper" @click.stop>
                <div class="block" >
                    <img :src="previewImg" ref="image"  style="width:100%;height:100%" alt="">
                </div>
                <div class="btn">
                    <van-button plain hairline size="small" type="warning" @click="show = false">取消</van-button>
                    <van-button plain hairline size="small"  type="primary" @click="uploadPhoto">确定</van-button>
                </div>
            </div>
        </van-overlay> -->
        <van-popup v-if="show" v-model="show" position="top" :style="{ height: '100%' }" >
            <update-photo  @close="closePhotoPopup" :file="file" :previewImg="previewImg"></update-photo>
        </van-popup>
    </div>
</template>

<script>
import { Dialog } from 'vant';
import UpdatePhoto from '@/views/profile/components/updatePhoto'
import { getUserProfile, changeUserPhoto ,editUserInfo} from '@/api/user'
import { removeItem }  from '@/utils/storage'

export default {
    name: 'settingIndex',
    components: {
        UpdatePhoto
    },
    data() {
        return {
            userInfo: {},
            isShowSettingUserName: false,
            userName: '',
            isShowSettingUserTro: false,
            userTro: '',
            showDate: false,
            minDate: new Date(2010, 0, 1),
            maxDate: new Date(2050, 0, 31),
            columns: ['男', '女'],
            showSexPick: false,
            fileList: [],
            show: false,
            file:null,
            previewImg: ''
        };
    },

    mounted() {
        this.loadUserProfile()
    },

    methods: {
        onClickLeft (){
            this.$router.go(-1)
        },
        // 获取用户个人资料
        async loadUserProfile () {
            const { data :{data}  } = await getUserProfile ()
            this.userInfo = data
            // console.log(data)
        },
        afterRead(file) {
        // this.file = null
        this.file = file.file
        // this.previewImg = window.URL.createObjectURL(this.file)
        console.log(this.file)
        this.show = true
        },
        // 上传头像
        uploadPhoto () {
            this.cropper && this.cropper.getCroppedCanvas().toBlob( async blob => {
                const fm = new FormData()
                fm.append('photo', blob)
                const { data } = await changeUserPhoto(fm)
                if (data.message === "OK") {
                    this.$toast.success('上传成功')
                    this.show = false
                    this.loadUserProfile()
                }
            })
        },

        ShowSettingUserName (userName) {
            this.isShowSettingUserName = true
            this.userName  = userName
        },
        ShowSettingUserTro (userTro) {
            this.isShowSettingUserTro = true
            this.userTro = userTro
        },
        pickDate () {
            this.showDate = true
        },
        // 调整日期格式
         formatDate(date) {
         return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
        },
        // 修改出生日期
        async onDateConfirm(date) {
          const birthday = this.formatDate(date)
          const  { data } = await editUserInfo ({
              birthday: birthday
          })
          if (data.message === 'OK') {
                this.$toast.success('修改成功')
                this.showDate = false
                this.loadUserProfile()
            }

        },
        // 修改性别
        async onConfirm(value, index) {
            // this.$toast(`当前值：${value}, 当前索引：${index}`);
            const { data }  = await editUserInfo ({
                gender: index
            })
            if (data.message === 'OK') {
                this.$toast.success('修改成功')
                this.showSexPick = false
                this.loadUserProfile()
            }
        },
        // 取消修改性别
        onCancel() {
        this.showSexPick = false
        },

        // 修改昵称
        async changeUserName () {
            const { data } = await editUserInfo ({
                name:this.userName
            })
            if (data.message === 'OK') {
                this.$toast.success('修改成功')
                this.isShowSettingUserName = false
                this.loadUserProfile()
            }
        },

        // 修改简介
        async changeUserTro () {
            const { data } = await editUserInfo ({
                intro: this.userTro
            })
            // console.log(data)
            if (data.message === 'OK') {
                this.$toast.success('修改成功')
                this.isShowSettingUserTro = false
                this.loadUserProfile()
            }
        },
        //退出登录
        logOut () {
            Dialog.confirm({
            title: '温馨提示',
            message: '亲，您确定要退出吗',
            theme: 'round-button',
            })
            .then(() => {
                removeItem('user-token')
                this.$store.commit('user/removeLoginInfo')
                this.$router.push({path:'/profile'})
            })
            .catch(() =>{

            })
            
        },
        initCropper () {
            const image = this.$refs.image;
            if (this.cropper){
                this.cropper.replace()
                return 
            }
                this.cropper = new Cropper(image, {
                viewMode: 1,
                dragMode: 'none',
                aspectRatio: 1,
                cropBoxResizable: false
            })
        },
        closePhotoPopup () {
            this.show = false
            // this.previewImg = ''
            this.file = null
           this.loadUserProfile()
        },
    },
}
</script>

<style lang="less" scoped>
.setting-container{
    height: 100%;
  .split{
      width: 100%;
      height: 12px;
      background-color: #f8f8f8;
  }
  .uploadImg{
      width: 100%;
      /deep/.van-uploader__wrapper{
          width: 100%;
           .van-uploader__input-wrapper{
            width: 100%;
      }
    }
     
  }
  .logout{
      position: absolute;
      bottom: 30%;
      width: 80%;
      left: 50%;
      transform: translateX(-50%);
  }
   .commentPopup{
    //  padding: 10px;
    height: 250px;
    /deep/.van-icon-close{
        color:#c8c9cc;
    }
   
    .van-field__value{
        padding-right: 10px;
    }
    .comment-content{
        
        .popup-header{
        padding: 10px;
        color: #666;
        font-weight: 500;
        font-size: .42667rem;
    }
         .comment-btn{
        position: absolute;
        bottom: 10px;
        .van-button__text{
            color: #fff;
        }
        
    }
        .comment-input {
            // padding: 10px;
            width: 80%;
            display: flex;
            justify-content: center;
            border: none;
            height: 80px;
            margin: 0 auto;
            textarea{
                border: none;
                font-size: 16px;
                width: 100%;
                height: 100%;
                color: #666;
                // word-break: b;
                background-color: #f7f8fa;
                border-radius: 10px;
                padding: 10px 10px;
            }
        }
    }
  }
  .wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .block {
    width: 80%;
    height: 300px;
    background-color: #fff;

  }
  .btn{
      display: flex;
      justify-content: space-between;
      position: absolute;
      left: 10px;
      right: 10px;
      bottom: 10px;
  }
}

</style>